package com.ctk.wifi.a.net;


import com.ctk.wifi.R;
import com.ctk.wifi.a.net.UDPSocketSend;
import com.ctk.wifi.a.net.UDPSocketReceive;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class UDPSocketActivity extends Activity {
	private Button send_bt = null;
    private TextView recv_tv = null;
    private EditText send_et = null;
    
    //Handler相关变量
    public static Handler mHandler;
    public static String content = ""; 
	 
	//Socket配置导入变量
    private String IpaddrInput;
    private int PortInput;
    
    //Socket发送变量
    private String mSend;
    
    //EditText暂存变量
    private String mEditText;
    
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_wifi_datatransmit);
        send_bt = (Button) findViewById(R.id.datatrans_send_button);
        recv_tv = (TextView)findViewById(R.id.datatrans_receive_textview);
        send_et = (EditText)findViewById(R.id.datatrans_send_edittext);
        
        //获取传递意图
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		IpaddrInput = bundle.getString("IpaddrInput");
		PortInput = Integer.parseInt(bundle.getString("PortInput"));
		
		mHandler = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				//recv_tv.setText(content);
				recv_tv.append(content);
			}
		};
		//UDP接收线程
		new Thread() {
			@Override
			public void run() {
				UDPSocketReceive server = new UDPSocketReceive();
				server.runReceive();
			}
		}.start(); 
		//UDP发送线程
		send_bt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mEditText= new String(send_et.getText().toString());
				//检测输入数据是否为空
				if (mEditText.length() == 0) {
					//recv_tv.setText("Please input something~");
					recv_tv.append("Please input something~\n");
				}
				else
				{
					new Thread() {
						@Override
						public void run() {
							CommunicationProtocols test = new CommunicationProtocols(mEditText.getBytes());
							try {
								mSend = test.buildDataPacket();
							} catch (Exception e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							
							UDPSocketSend client = new UDPSocketSend(mSend);
							client.send(IpaddrInput, PortInput);
							 
							//通信协议解析输出信息
							try {
								test.output();
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}.start();
				}
			}
		});
	}
}